package com.yuma.springshiroredisthymeleaf.controller;

import com.yuma.springshiroredisthymeleaf.common.ResultEnum;
import com.yuma.springshiroredisthymeleaf.exception.GoodsException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

    Subject subject;
    @RequestMapping("/logout")
    public String logout() {
        if (subject != null && subject.isAuthenticated()){
            subject.logout();  // 清空shiro提供的session
        }
        return "/login";     // 登录页面
    }

    @RequestMapping("/login")
    public String login(String name,String password){
        subject = SecurityUtils.getSubject();
        //把当前密码加密
        String md5pass = DigestUtils.md5DigestAsHex(password.getBytes());
        UsernamePasswordToken token = new UsernamePasswordToken(name, md5pass);
        try {
            subject.login(token);
            token.setRememberMe(true); // session中记录
            // 如果登录成功，重定向
            if (subject.isAuthenticated()){
                return "redirect:/goods/getAll/1/2";
            }else{
                token.clear();
                return "redirect:/login";
            }
        }catch (UnknownAccountException e){
            throw new GoodsException(ResultEnum.NO_ACCOUNT.getCode(),ResultEnum.NO_ACCOUNT.getMsg());
        }catch (IncorrectCredentialsException e){
            throw new GoodsException(ResultEnum.WRONG_PASSWORD.getCode(),ResultEnum.WRONG_PASSWORD.getMsg());
        }
    }
}